<?php
class Zendvn_Model_Table_User extends Zend_Db_Table{
	protected $_name = "users";
	protected $_primary = "id"; 
	
	public function statusItem($arrParam = null,$options = null){
		if($options == null){
			$status = ($arrParam['status'] == 'active' )?'inactive':'active';	
			$itemInfo = $this->getItem(array('id'=>(int)$arrParam['id']));
			$data = array('status'=>$status);
			$where = 'id = ' . (int)$arrParam['id'];
			$this->update($data, $where);
		}
		
		if($options['task'] == 'multi'){
			$status = $arrParam['status'];				
			if(count($arrParam['cid'])>0){
				if($status == 'active'){
					$ids = implode(',', $arrParam['cid']);
					$where = 'id IN (' . $ids . ')';
					$data = array('status'=>$status);
					$this->update($data, $where);
				}else{
					foreach ($arrParam['cid'] as $val){
						$itemInfo = $this->getItem(array('id'=>(int)$val));
						$where = 'id = ' . $val;
						$data = array('status'=>$status);
						$this->update($data, $where);
					}
				}
			}
		}
	}
	
	public function deleteItem($arrParam = null,$options = null){
		$model = new Zendvn_Model_DeleteRecode();
		$model->user($arrParam,$options,$this);
	}
	
	public function getItem($arrParam = null,$options = null){
		$db = $this->getAdapter();
		
		if($options == null){
			$where = 'id = ' . (int)$arrParam['id'];
			$res = $this->fetchRow($where);
			if(is_object($res)){
				$result = $res->toArray();
			}
		}
		
		if($options['task'] == 'check-email'){
			$where = 'email = "' . $arrParam['email'] . '"';
			$result = $this->fetchRow($where);
		}
		
		if($options['task'] == 'info'){
			$select = $db->select()
						->from(array('u' => $this->_name))
						->joinLeft('user_and_group AS uag', 'u.id = uag.user_id',array())
					 	->joinLeft('user_group AS g', 'g.id = uag.user_group_id', array('g.name as group_name', 'g.id AS group_id'))
						->where('u.id = ?',$arrParam['id'],1);
			$result = $db->fetchRow($select);
			
		}
		return $result;
	}
	
	public function listItem($arrParam = null, $options = null){

		$db = $this->getAdapter();	
		if($options['task'] == 'list-dbtable'){
			$aColumns = array('u.id', 'u.id','u.email', 'CONCAT(first_name, " ", last_name)', 'u.status', 'u.birthday', 'g.name', 'u.created');
			$select = $db->select()
						 ->from(array('u' => $this->_name), array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS u.id'), 'u.id','CONCAT(first_name, " ", last_name) AS fullname', 'email', 'birthday', 'g.name AS group_name', 'created', 'u.id AS DT_RowId', 'status'))
						 ->joinLeft(array('uag' => 'user_and_group'), 'u.id = uag.user_id', null)
					 	 ->joinLeft(array('g' => 'user_group'), 'g.id = uag.user_group_id', null);
			
			//======================= SEARCH =================
			$sWhere = "";
			if (@$arrParam['sSearch'] != "" ){
				$keyword = "%" . mysql_real_escape_string($arrParam['sSearch']) . "%";
				foreach($aColumns as  $value){
					$sWhere .= $value . " LIKE '" . $keyword . "' OR ";
				}
				$sWhere = substr_replace( $sWhere, "", -3 );
			}
			/* Individual column filtering */
			for($i=0; $i<count($aColumns); $i++ ){
				if ( @$arrParam['bSearchable_'.$i] == "true" && $arrParam['sSearch_'.$i] != '' ){
					if ($sWhere == "" ){
						$sWhere = "WHERE ";
					}else{
						$sWhere .= " AND ";
					}
					$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
				}
			}
			if($sWhere != ""){
				$select->where($sWhere);
			}
			//======================= Paging =================
			$sLimit = "";
			if(isset($arrParam['iDisplayStart'] ) && $arrParam['iDisplayLength'] != '-1'){
				$start = mysql_real_escape_string($arrParam['iDisplayStart']);
				$length = mysql_real_escape_string($arrParam['iDisplayLength']);
				$page = ($start / $length) + 1;
				$select->limitPage($page, $length);
			}
			//======================= Ordering =================
			$sOrder = '';
			if (isset($arrParam['iSortCol_0'])){
				for ( $i=0 ; $i<intval( $arrParam['iSortingCols'] ) ; $i++ ){
					if ( $arrParam[ 'bSortable_'.intval($arrParam['iSortCol_'.$i]) ] == "true"){
						$sOrder .= $aColumns[intval( $arrParam['iSortCol_'.$i] ) ]."
						 	".mysql_real_escape_string( $arrParam['sSortDir_'.$i] ) .", ";
					}
				}
				$sOrder = substr_replace( $sOrder, "", -2 );
				$select->order($sOrder);
			}
			
			$result['data'] = $db->fetchAll($select);
            $result['total'] = $db->fetchOne('SELECT FOUND_ROWS()');
		}		 
		return $result;
	}
	
	public function saveItem($arrParam = null,$options = null){
		$function  = Zendvn_System_Function::call($options['task']);
		$this->$function($arrParam);
	}
	
	public function adminAdd($arrParam = null){
		$row = $this->fetchNew();
		$row->avatar		= $arrParam['avatar'];			
		$row->password		= Zendvn_Encode_Password::encode($arrParam['password']);
		$row->email			= $arrParam['email'];
		$row->first_name	= $arrParam['first_name'];
		$row->last_name		= $arrParam['last_name'];
		$row->birthday		= $arrParam['birthday'];
		 	 	 	 	 	 	 	 	
		$row->status		= ($arrParam['status']=='') ? 'inactive':$arrParam['status'];
		$row->created		= date('Y-m-d H:i:s');
		$row->created_ip 	= $_SERVER['REMOTE_ADDR'];
			
		$row->save();
			
		$userID = $row->id;
			
		$db = $this->getAdapter();
		
		$bind = array('user_id'=>$userID,'user_group_id'=>$arrParam['group_id'],'group_default'=>1);
		$db->insert('user_and_group', $bind);
		
		$ext_group = $arrParam['ext_group'];
		if(count($ext_group)>0){
			foreach ($ext_group as $key => $val){					
				if($val!= 0 && $val!= 5 && $val != $arrParam['group_id']){
					$extArray[] = $val;
				}
			}
			if(count($extArray)>0){
				foreach ($extArray as $key => $val){	
					$bind = array('user_id'=>$userID,
								  'user_group_id'=>$val,
								  'group_default'=>0);
					$db->insert('user_and_group', $bind);
				}
			}
		}
	}
	
	public function adminEdit($arrParam = null){
		
		$where  = 'id = ' . (int)$arrParam['id'];
		$row = $this->fetchRow($where);
		$row->avatar		= $arrParam['avatar'];		
		if(trim($arrParam['password'])!= ''){	
			$row->password		= Zendvn_Encode_Password::encode($arrParam['password']);
		}
		$row->email			= $arrParam['email'];
		$row->first_name	= $arrParam['first_name'];
		$row->last_name		= $arrParam['last_name'];
		$row->birthday		= $arrParam['birthday'];
			
		$row->status		= ($arrParam['status']=='') ? 'inactive':$arrParam['status'];
		
		$row->save();
	
		$userID = $row->id;
			
		$db = $this->getAdapter();
		$where = 'user_id = ' . $userID;
		$db->delete('user_and_group',$where);
		$bind = array('user_id'=>$userID,'user_group_id'=>$arrParam['group_id'],'group_default'=>1);
		$db->insert('user_and_group', $bind);
			
		$ext_group = $arrParam['ext_group'];
		if(count($ext_group)>0){
			foreach ($ext_group as $key => $val){					
				if($val!= 0 && $val != $arrParam['group_id']){
					$extArray[] = $val;
				}
			}
			
			if(count($extArray)>0){
				foreach ($extArray as $key => $val){	
					$bind = array('user_id'=>$userID,
								  'user_group_id'=>$val,
								  'group_default'=>0);
					$db->insert('user_and_group', $bind);
				}
			}
		}
	}
	
	public function getConfirmCode($arrParam,$options=null){
		$auto_code = new Zendvn_RandomString();
		$confirm_code = $auto_code->createRandomString(11);
		
		$encode = new Zendvn_Encode_Password();
		$pass = $encode->encode($confirm_code);
		
		if($options['task'] == 'user-active'){
			$code = 'active_code';
		}else{
			$code = 'confirm_code';
		}
		$result = $this->fetchRow('email="'.$arrParam['email'].'"');
		
		$result->$code = $pass;
		$result->save();
		
		if(is_object($result)){
			$result = $result->toArray();
		}
		
		$result[$code] = $confirm_code;
		
		return $result;
	}
	
	public function updatePass($arrParam, $options = null){
		if(empty($arrParam['id'])) return false;
		if($options == null){
			$result = $this->update(
				array(
					'password'=>$arrParam['confirm_code'],
					'confirm_code'=>'',
					'status'=>'active'
				),
				'id = '.$arrParam['id']
			);
		}
		
		if($options['task'] == 'user-active'){
			$result = $this->update(
				array(
					'status' => 'active',
					'active_code'=>''
				),
				'id = '.$arrParam['id']
			);
		}
		return $result;
	}
}
























